package com.zwr.normal.sharemodel.juc;

import java.math.BigDecimal;
import java.util.concurrent.atomic.AtomicReference;

public class DecimalAccountNoLock implements DecimalAccount{
    AtomicReference<BigDecimal> decimalReference;

    public DecimalAccountNoLock(BigDecimal balance) {
        this.decimalReference = new AtomicReference<>(balance);
    }
    @Override
    public BigDecimal getBalance() {
        return decimalReference.get();
    }

    @Override
    public void withdraw(BigDecimal amount) {
        while (true){
            BigDecimal pre = decimalReference.get();
            BigDecimal next = pre.subtract(amount);
            if (decimalReference.compareAndSet(pre, next)) {
                break;
            }
        }
    }
}
